package com.yupi.springbootinit.controller;

import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.DevOrProdType;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.model.dto.orders.OrderCreateRequest;
import com.yupi.springbootinit.model.vo.OrdersVO;
import com.yupi.springbootinit.model.vo.UserVO;
import com.yupi.springbootinit.service.OrdersService;
import com.yupi.springbootinit.service.UserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/orders")
@CrossOrigin(origins = {DevOrProdType.devString},allowCredentials = "true")
public class OrdersController {
    @Resource
    private OrdersService ordersService;

    @Resource
    private UserService userService;

    /**
     * 创建订单
     * @param orderCreateRequest
     * @param request
     * @return
     */
    @PostMapping("/create")
    public BaseResponse<Long> CreateOrder(@RequestBody OrderCreateRequest orderCreateRequest, HttpServletRequest request){
        if(orderCreateRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        UserVO loginUser = userService.getLoginUser(request);
        Long result = ordersService.crateOrder(orderCreateRequest,loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 查询我创建的订单
     */
    @GetMapping("/query")
    public BaseResponse<List<OrdersVO>> QueryMyOrders(HttpServletRequest request){
        UserVO loginUser = userService.getLoginUser(request);
        if(loginUser == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        List<OrdersVO> ordersVOList = ordersService.queryMyOrders(loginUser);
        return ResultUtils.success(ordersVOList);
    }


}
